﻿using System;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using C2C.FileSystem;

namespace LeiRay
{
    public partial class Form1 : Form
    {
        private LeiRayConfiguration leiRayConfiguration { get; set; }

        private FileSystemWatcher fileSystemWatcher { get; set; }

        private TreeViewState treeViewState { get; set; }

        public Form1()
        {
            InitializeComponent();
            leiRayConfiguration = new LeiRayConfiguration();
            Init();
        }

        private void Init()
        {
            if(!leiRayConfiguration.Location.IsEmpty)
            {
                Location = leiRayConfiguration.Location;
            }

            if(!leiRayConfiguration.Size.IsEmpty)
            {
                Size = leiRayConfiguration.Size;
            }
            treeViewState = new TreeViewState(fileSystemTreeView1);
            SetListBoxButtonsEnableState(false);
            SetBtnMergeState();
            InitDir();
        }

        private void InitDir()
        {
            if(fileSystemWatcher != null)
            {
                fileSystemWatcher.Dispose();
            }

            fileSystemWatcher = new FileSystemWatcher(leiRayConfiguration.Directory);
            fileSystemWatcher.EnableRaisingEvents = true;
            fileSystemWatcher.Changed += fileSystemWatcher_Changed;
            fileSystemWatcher_Changed(null, null);
        }

        void fileSystemWatcher_Changed(object sender, FileSystemEventArgs e)
        {
            MethodInvoker method = delegate
                {
                    treeViewState.SaveTreeView();
                    fileSystemTreeView1.Load(leiRayConfiguration.Directory);
                    treeViewState.RestoreTreeView();
                };
            if (InvokeRequired)
                BeginInvoke(method);
            else
                method.Invoke();
            
        }

        private void previewHandlerHost1_Resize(object sender, EventArgs e)
        {
            if (fileSystemTreeView1.SelectedNode is FileNode)
            {
                previewHandlerHost1.Open(((FileNode)fileSystemTreeView1.SelectedNode)._fileInfo.FullName);    
            }
        }

        private void fileSystemTreeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node.Nodes.Count == 0 && e.Node is FileNode)
            {
                previewHandlerHost1.Open(((FileNode)e.Node)._fileInfo.FullName);
            }
            else
            {
                previewHandlerHost1.UnloadPreviewHandler();
            }
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            DialogResult dialogResult = folderBrowserDialog1.ShowDialog(this);
            if(dialogResult == DialogResult.OK)
            {
                leiRayConfiguration.Directory = folderBrowserDialog1.SelectedPath;
                InitDir();
            }
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            MessageBox.Show(this, "את כן אלטרואיסטית");
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            leiRayConfiguration.Location = Bounds.Location;
            leiRayConfiguration.Size = Bounds.Size;
        }

        private void fileSystemTreeView1_ItemDrag(object sender, ItemDragEventArgs e)
        {
            DoDragDrop(e.Item, DragDropEffects.Copy | DragDropEffects.Move);
        }

        private void fileSystemTreeView1_DragEnter(object sender, DragEventArgs e)
        {
            e.Effect = e.AllowedEffect;
        }

        private void listBox1_DragEnter(object sender, DragEventArgs e)
        {
            FileNode node = (FileNode)e.Data.GetData(typeof(FileNode));
            if (node == null)
            {
                return;
            }
            e.Effect = e.AllowedEffect;
        }

        private void listBox1_DragDrop(object sender, DragEventArgs e)
        {
            FileNode node = (FileNode)e.Data.GetData(typeof(FileNode));
            if(node == null)
            {
                return;
            }
            listBox1.Items.Add(node);
            SetBtnMergeState();
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            SetListBoxButtonsEnableState(listBox1.SelectedItem != null);
        }

        private void SetListBoxButtonsEnableState(bool state)
        {
            btnUp.Enabled = btnDown.Enabled = btnRemove.Enabled = state;
        }

        private void btnUp_Click(object sender, EventArgs e)
        {
            int selectedIndex = listBox1.SelectedIndex;
            object selectedItem = listBox1.SelectedItem;
            listBox1.Items.RemoveAt(selectedIndex);
            int newSelectedIndex = Math.Max(selectedIndex - 1, 0);
            listBox1.Items.Insert(newSelectedIndex, selectedItem);
            listBox1.SelectedIndex = newSelectedIndex;
            listBox1.Select();
        }

        private void btnDown_Click(object sender, EventArgs e)
        {
            int selectedIndex = listBox1.SelectedIndex;
            object selectedItem = listBox1.SelectedItem;
            listBox1.Items.RemoveAt(selectedIndex);
            int newSelectedIndex = Math.Min(selectedIndex + 1, listBox1.Items.Count);
            listBox1.Items.Insert(newSelectedIndex, selectedItem);
            listBox1.SelectedIndex = newSelectedIndex;
            listBox1.Select();
        }

        private void btnRemove_Click(object sender, EventArgs e)
        {
            int selectedIndex = listBox1.SelectedIndex;
            listBox1.Items.RemoveAt(selectedIndex);
            listBox1.Select();
            SetBtnMergeState();
        }

        private void SetBtnMergeState()
        {
            btnJoin.Enabled = listBox1.Items.Count > 0;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            DialogResult dialogResult = saveFileDialog1.ShowDialog(this);
            if(dialogResult == DialogResult.OK)
            {
                try
                {
                    MsWord.Merge(listBox1.Items.Cast<FileNode>().Select(fn => fn._fileInfo.FullName).ToArray(), saveFileDialog1.FileName, true);
                    if (chkRemoveOriginalFiles.Checked)
                    {
                        try
                        {
                            foreach (var item in listBox1.Items.Cast<FileNode>().Select(fn => fn._fileInfo.FullName))
                            {
                                File.Delete(item);
                            }
                        }
                        catch (Exception exception)
                        {
                            MessageBox.Show(this, "Failed to remove existing files: " + exception, "Failed to remove existing files",
                                MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        }

                        listBox1.Items.Clear();
                    }
                }
                catch(Exception exception)
                {
                    MessageBox.Show(this, "Failed to merge documents: " + exception, "Failed to merge documents",
                                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
        }
    }
}
